package com.itic.mall.system.goods.goodssku.service;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.type.CouponType;
import com.itic.appbase.framework.type.SkuType;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.goods.vo.GoodsDetailVo;
import com.itic.mall.system.goods.goodsspu.service.GoodsSpuService;
import com.itic.mall.system.goods.skucoupon.service.SkuCouponService;
import com.itic.mall.system.goods.skuproperty.service.SkuPropertyService;
import com.itic.mall.system.inter.goods.goodssku.persistence.dao.GoodsSkuDao;
import com.itic.mall.system.inter.goods.goodssku.persistence.model.GoodsSku;
import com.itic.mall.system.inter.goods.goodssku.persistence.model.GoodsSkuExample;
import com.itic.mall.system.inter.goods.goodssku.persistence.model.GoodsSkuExample.Criteria;
import com.itic.mall.system.inter.goods.goodsspu.persistence.model.GoodsSpu;
import com.itic.mall.system.inter.goods.skucoupon.persistence.model.SkuCoupon;
import com.itic.mall.system.inter.goods.skuproperty.persistence.model.SkuProperty;
import com.itic.mall.system.orders.item.service.OrdersItemService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class GoodsSkuService
     extends CrudService<GoodsSkuDao,GoodsSku,GoodsSkuExample> {
    @Autowired
    private GoodsSkuDao goodsSkuDao;
    @Autowired
    private SkuPropertyService skuPropertyService;
    @Autowired
    private GoodsSpuService goodsSpuService;
    @Autowired
    private OrdersItemService ordersItemService;
    @Autowired
    private SkuCouponService skuCouponService;

    /**
	 * 根据skuId,count 查询库存
	 * @author 王文鑫
	 * @date 2018年1月12日 上午10:38:41
	 * @param Skuid
	 * @param count
	 * @return
	 */
	public int getTotalInventoryBySkuIdAndcount(String id,int count) {
		int total = 0;
		
		if(!StringHelper.isBlank(id) && count != 0){
			GoodsSku GoodsSku = get(id);
			int couSku = GoodsSku.getTotalInventory();
			if(couSku > count){
				total = goodsSkuDao.getTotalInventoryBySkuIdAndcount(id);
			}
		}
		return total ; 
	}
	
	public Integer getTotalSalesBySpuId(String id) {
		return goodsSkuDao.getTotalSalesBySpuId(id);
	}
	/**
	 * 整点特卖商品编辑
	 * @param spuIds
	 * @param wlcommisoins
	 * @param maxBuyNums
	 * @return
	 */
	public String updateGoodsSku(List<String> spuIds,List<Double> wlcommisoins,List<Integer> maxBuyNums){
    	String result = ResponseCode.SERVER_ERROR.getCode();
    	if(spuIds.size()>0 && wlcommisoins.size()>0 && maxBuyNums.size()>0 && 
    			wlcommisoins.size() == maxBuyNums.size() && spuIds.size() == maxBuyNums.size()){
    		for(int i=0;i<spuIds.size();i++){
    			List<GoodsSku> list = getGoodsSkuBySpuId(spuIds.get(i));
    			for(GoodsSku goodsSku:list){
    				if(wlcommisoins.get(i) != null || maxBuyNums.get(i) != null){
    					if(wlcommisoins.get(i) != null){
    	    				goodsSku.setSkuProfit(wlcommisoins.get(i));
    					}
    					if(maxBuyNums.get(i) != null){
    	    				goodsSku.setMaxBuyNum(maxBuyNums.get(i));
    					}
    					int back = this.goodsSkuDao.updateByPrimaryKey(goodsSku);
        				if(back == 1){
        					result = ResponseCode.SUCCESS.getCode();
        				}
    				}else{
    					result = ResponseCode.SUCCESS.getCode();
    				}
    			}
    		}
    	}
    	return result;
	}
	/**
	 * 修改单个特卖商品的信息
	 * @param spuId
	 * @param wlcommission
	 * @param maxCount
	 * @return
	 */
	public String updateOneGoodsSku(String spuId,Double wlcommission,Integer maxCount){
    	String result = ResponseCode.SERVER_ERROR.getCode();
    	if(StringHelper.isNotBlank(spuId) && wlcommission != null && maxCount != null){
    		GoodsSku goodsSku = getOneGoodsSkuBySpuId(spuId);
    		if(goodsSku != null){
    			if(wlcommission != null || maxCount != null){
    				if(wlcommission != null){
    	    			goodsSku.setSkuProfit(wlcommission);
    				}
    				if(maxCount != null){
    	    			goodsSku.setMaxBuyNum(maxCount);	
    				}
    				int back = this.goodsSkuDao.updateByPrimaryKey(goodsSku);
        			if(back == 1){
        				result = ResponseCode.SUCCESS.getCode();
        			}
    			}
    		}
    	}
    	return result;
	}
	/**
	 * 获取单个商品信息
	 * @param spuId
	 * @return
	 */
	public GoodsSku getOneGoodsSkuBySpuId(String spuId){
		GoodsSku goodsSku = null;
		if(StringHelper.isNotBlank(spuId)){
			GoodsSkuExample example = new GoodsSkuExample();
			Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andSpuIdEqualTo(spuId);
			List<GoodsSku> list = this.goodsSkuDao.selectByExample(example);
			if(list.size()>0){
				goodsSku = list.get(0);
			}
		}
		return goodsSku;
	}
	
	/**
	 * 获取商品最大可购买数量
	 * @param spuId
	 * @return
	 */
	public Integer getMaxCount(String spuId){
		Integer maxCount = 0;
		List<GoodsSku> list = null;
		if(StringHelper.isNotBlank(spuId)){
			GoodsSkuExample example = new GoodsSkuExample();
			Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andSpuIdEqualTo(spuId);
			list = this.goodsSkuDao.selectByExample(example);
			for(GoodsSku goodsSku:list){
				if(goodsSku.getMaxBuyNum() != null){
					maxCount = maxCount + goodsSku.getMaxBuyNum();
				}
			}
		}
		return maxCount;
	}
	/**
	 * 修改最大购买数量
	 * @param spuId
	 * @param maxCount
	 * @return
	 */
	public String updateGoodsSku(String spuId,Integer maxCount){
    	String result = ResponseCode.SERVER_ERROR.getCode();
		if(StringHelper.isNotBlank(spuId) && maxCount != null){
			List<GoodsSku> list = getGoodsSkuBySpuId(spuId);
			if(list.size()>0){
				for(GoodsSku goodsSku:list){
					goodsSku.setMaxBuyNum(maxCount);
					int back = this.goodsSkuDao.updateByPrimaryKey(goodsSku);
					if(back == 1){
						result = ResponseCode.SUCCESS.getCode();
					}
				}
			}
		}
		return result;
	} 
	/**
	 * 根据skuNum获取sku
	 * @author 王文鑫
	 * @date 2018年1月19日 下午4:24:40
	 * @param id
	 * @return
	 */
	public GoodsSku getSkuByskuNum(String skuNum) {
		return goodsSkuDao.getSkuByskuNum(skuNum);
	}
	/**
	 * 根据spuId 删除sku
	 * @author 王文鑫
	 * @date 2018年2月8日 下午8:00:26
	 * @param spuId
	 * @return
	 */
	public boolean deleteBySpuId(String spuId) {
		return goodsSkuDao.deleteBySpuId(spuId);
	}
	
	/**
	 * 根据skuId获取sku
	 * @author 王文鑫
	 * @date 2018年1月12日 上午9:36:05
	 * @param skuId
	 * @return
	 */
	public GoodsSku getSkuBySkuId(String skuId) {
		return get(skuId);
	}
	
	/**
	 * 根据spuId 获取sku
	 * @author 王文鑫
	 * @date 2018年2月7日 下午4:45:43
	 * @param spuId
	 * @return
	 */
	public List<GoodsSku> getGoodsSkuBySpuId(String spuId) {
		return goodsSkuDao.getGoodsSkuBySpuId(spuId);
	}
	
	/**
	 * 根据 spuId、propertyId查询sku
	 * @author 王文鑫
	 * @date 2018年2月10日 上午11:12:58
	 * @param spuId
	 * @param propertyId
	 * @return
	 */
	public GoodsSku getGoodsSkuBySpuIdPropertyId(String spuId,String propertyId) {
		return goodsSkuDao.getGoodsSkuBySpuIdPropertyId(spuId,propertyId);
	}
	
	/**
	 * 根据组合比查询sku
	 * @author 王文鑫
	 * @date 2018年1月16日 上午11:01:01
	 * @param ParmQuery
	 * @return
	 */
	public List<GoodsSku> getGoodsSkuByParmquery(String ParmQuery) {
		return goodsSkuDao.getGoodsSkuByParmquery(ParmQuery);
	}
	
	/**
	 * 根据规格ID查看规格并返回map
	 * */
	public Map<String, Object> getGoodSkuById(String skuId){
		GoodsSku goodsSku = this.get(skuId);
		Map<String,Object> skuMap = new HashMap<String, Object>();
		if(goodsSku !=null) {
			String paramQuery = goodsSku.getParamQuery();
			if(StringUtils.isNotEmpty(paramQuery)) {
				String propertys [] = paramQuery.split(":");
				skuMap = this.parseSku(propertys);
			}
		}
		return skuMap;
	}
	public Map<String, Object> getGoodSkuparamsById(String skuId){
		GoodsSku goodsSku = this.get(skuId);
		Map<String,Object> skuMap = new HashMap<String, Object>();
		if(goodsSku !=null) {
			String paramQuery = goodsSku.getParamQuery();
			if(StringUtils.isNotEmpty(paramQuery)) {
				String propertys [] = paramQuery.split(":");
				skuMap = this.getSku(propertys);
			}
		}
		return skuMap;
	}
	
	private Map<String, Object> getSku(String []propertys){
		Map<String, Object> map = new HashMap<String, Object>();
		for(String property :propertys ) {
			SkuProperty skuProperty = this.skuPropertyService.get(property);
			if(skuProperty != null){
				SkuType type = SkuType.getSkuType(skuProperty.getName());
				map.put(type.getName(), skuProperty.getValue());
			}
		}
		return map;
	}
	
	private Map<String, Object> parseSku(String []propertys){
		Map<String, Object> map = new HashMap<String, Object>();
		for(String property :propertys ) {
			SkuProperty skuProperty = this.skuPropertyService.get(property);
			if(skuProperty!=null){
				//SkuType type = SkuType.getSkuType(skuProperty.getName());
				map.put(skuProperty.getName(), skuProperty.getValue());
			}
		}
		return map;
	}
	
	/**
	 * 根据SkuID获取商品信息
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @param goodsId
	 * @return
	 */
	public GoodsDetailVo getSkuDetailBySkuId(String skuId,int count) {
			GoodsDetailVo Vo = new GoodsDetailVo();
				GoodsSpu goodsSpu = this.goodsSpuService.getBySku(skuId);
				if(goodsSpu!=null){
					if(goodsSpu.getIsSysCoupon()!=null&&"1".endsWith(goodsSpu.getIsSysCoupon()))
						Vo.setIsUseSysCoupon("1");
					else
						Vo.setIsUseSysCoupon("0");
					if(goodsSpu.getIsJifenExchange()!=null&&"1".endsWith(goodsSpu.getIsJifenExchange()))
						Vo.setIsUsePoint("1");
					else
						Vo.setIsUsePoint("0");
					GoodsSku goodsSku = this.get(skuId);
					if(goodsSku!=null){
						Vo.setGoodsImg(goodsSpu.getMainImageUrl());// 图片  
						Vo.setGoodsName(goodsSpu.getGoodsName());// 名称
						Vo.setOrginPrice(goodsSku.getSkuPrice()==null?0:goodsSku.getSkuPrice());
						//TODO 计算一件商品的现价
						double couponPrice = this.calSkuCouponPrice(skuId);
						
						Vo.setPrice(couponPrice);
						Vo.setCount(count);
						Vo.setGoodsId(skuId);
						// 商品规格属性
						Map<String, Object> paramMap =this.getGoodSkuById(skuId);
						Vo.setParam(paramMap);// 商品规格参数
					}
				}
			return Vo;
	}
	/**
	 * 根据skuId获取商品规格的优惠价格
	 * @param skuId
	 * @return
	 */
	private  double calSkuCouponPrice(String skuId) {
    	GoodsSpu goodsSpu = this.goodsSpuService.getBySku(skuId);
		GoodsSku goodsSku = this.getSkuBySkuId(skuId);
		double couponPrice = goodsSku.getSkuPrice()==null?0:goodsSku.getSkuPrice();
		if(goodsSku!=null) {
			double price = goodsSku.getSkuPrice()==null?0:goodsSku.getSkuPrice();
			//获取商品的优惠券
			SkuCoupon skuCoupon = this.skuCouponService.getSkuCouponByGoodId(goodsSpu.getId());
			if(skuCoupon!=null){
				CouponType couponType = CouponType.getCouponType(skuCoupon.getType());
				switch (couponType) {
				case pack:
				case coupon:
					price = price - (skuCoupon.getMoney() ==null?0:skuCoupon.getMoney());
					break;
				case fullcut:
					double fullMoney = skuCoupon.getLimitFullMoney()==null?0:skuCoupon.getLimitFullMoney();
					if(price >fullMoney)
						price = price- skuCoupon.getMoney();
					break;
				}
				price = price <=0?couponPrice:price;
				couponPrice = price;
			}
		}
		return couponPrice;
	}
}